<template>
  <el-drawer :z-index="50" size="650" v-model="visible" title="新增班级" :before-close="handleClose" :close-on-click-modal="false" destroy-on-close>
    <el-form class="form" ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item label="班级名称" prop="arrangeName">
        <el-input v-model="form.arrangeName" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="所属课程" prop="courseId">
        <el-select v-model="form.courseId" placeholder="请选择所属课程" filterable>
          <el-option v-for="item in props.enumMap.courseList" :label="item.courseName" :value="item.courseId"
            :key="item.departId" />
        </el-select>
      </el-form-item>
      <div class="flex-item">
        <el-form-item label="总课节数（节）" prop="outlineTotalCount">
          <el-input v-model="form.outlineTotalCount" v-int="200" placeholder="请输入总课节数(1-200)">
            <template #append>节</template>
          </el-input>
        </el-form-item>
        <el-form-item label="课程单价" prop="arrangeOutlinePrice">
          <el-input v-price v-model="form.arrangeOutlinePrice" placeholder="请输入课程单价">
            <template #append>元 / 节</template>
          </el-input>
        </el-form-item>
      </div>
      <el-form-item label="课程总价（元）" prop="arrangeSalePrice">
        <el-input v-price v-model="form.arrangeSalePrice" placeholder="请输入课程总价" />
      </el-form-item>
      <div class="flex-item">
        <el-form-item label="开班人数" prop="arrangeMinCapacity">
          <el-input v-int v-model="form.arrangeMinCapacity" placeholder="请输入开班人数" />
        </el-form-item>
        <el-form-item label="满班人数" prop="arrangeMaxCapacity">
          <el-input v-int v-model="form.arrangeMaxCapacity" placeholder="请输入满班人数" />
        </el-form-item>
      </div>
      <el-form-item label="上课时间" prop="arrangeTimeList" required>
        <div class="time-box" v-for="(item, index) in form.arrangeTimeList" :key="index">
          <el-select class="select-item" v-model="item.week" placeholder="请选择">
            <el-option :label="item.label" :value="item.week" :key="item.week"
              v-for="item in arrangeTimeWeek" />
          </el-select>
          <div class="select-time-box">
            <el-time-picker class="select-item" placeholder="上课时间" v-model="item.startTime" format="HH:mm"
              value-format="HH:mm"></el-time-picker>
            <span class="fix">~</span>
            <el-time-picker class="select-item" placeholder="下课时间" v-model="item.endTime" format="HH:mm"
              value-format="HH:mm"></el-time-picker>
          </div>
          <div class="flex">
            <el-icon v-if="form.arrangeTimeList.length - 1 === index" @click="handleAddTime()" class="mr10 cursor"
              color="#666" size="16">
              <Plus />
            </el-icon>
            <el-icon v-if="form.arrangeTimeList.length > 1" @click="handleDelTime(index)" class="cursor" color="#666"
              size="16">
              <Minus />
            </el-icon>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="上课时间说明" prop="buyNoticeContent">
        <el-input v-model="form.buyNoticeContent" type="textarea" placeholder="请输入购买须知" :rows="10" show-word-limit
          maxlength="1000" />
      </el-form-item>
      <el-form-item label="开课时间段" prop="signupStartTime">
        <div class="flex-item">
          <el-date-picker v-model="form.signupStartTime" type="datetime" format="YYYY-MM-DD hh:mm"
            value-format="YYYY-MM-DD hh:mm:ss" placeholder="请选择开课时间" />
          <span class="fix ml14">~</span>
          <el-date-picker v-model="form.signupEndTime" type="datetime" format="YYYY-MM-DD hh:mm"
            value-format="YYYY-MM-DD hh:mm:ss" placeholder="请选择结课时间" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { reactive, ref, nextTick } from 'vue';
import { AddArrange, SaveArrange, GetArrangeInfo } from '@/api/modules/service'
import { dayjs, ElMessage, FormInstance, FormRules } from 'element-plus';

const arrangeTime = {
  week: '',
  endTime: '',
  startTime: '',
}
const visible = ref<boolean>(false)
const type = ref<string>('')
const props = ref()
const arrangeTimeWeek = ref([
  { label: '周一', value: '周一', week: 1 },
  { label: '周二', value: '周二', week: 2 },
  { label: '周三', value: '周三', week: 3 },
  { label: '周四', value: '周四', week: 4 },
  { label: '周五', value: '周五', week: 5 },
  { label: '周六', value: '周六', week: 6 },
  { label: '周日', value: '周日', week: 0 },
])
let form = reactive<any>({
  buyNoticeSwitch: 0,
  arrangeTimeList: [
    { week: '', startTime: '', endTime: '' }
  ],
  limitGrade: [],
  limitClass: [],
  signupStartTime: '',
  signupEndTime: '',
  courseNo: '',
  arrangeNo: '',
  buyNoticeContent: '',
  arrangeDesc: ''
})
const rules = reactive<FormRules>({
  arrangeName: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
  ],
  courseId: [
    { required: true, message: '请选择所属课程', trigger: 'change' }
  ],
  outlineTotalCount: [
    { required: true, message: '请输入总课节数', trigger: 'blur' },
  ],
  arrangeOutlinePrice: [
    { required: true, message: '请输入课程单价', trigger: 'blur' },
  ],
  arrangeCapacity: [
    { required: true, message: '请输入招生人数', trigger: 'blur' },
  ],
  arrangeSalePrice: [
    { required: true, message: '请输入课程总价', trigger: 'blur' },
  ],
  arrangeMinCapacity: [
    { required: true, message: '请输入开班人数', trigger: 'blur' },
  ],
  arrangeMaxCapacity: [
    { required: true, message: '请输入满班人数', trigger: 'blur' },
  ],
})
/** 接收父组件传过来的参数 */
async function acceptParams(params: Partial<any> = {}, acceptType: string) {
  type.value = acceptType
  visible.value = true;
  props.value = params
  if (acceptType === 'edit' || acceptType === 'copy') {
    const { data }: any = await GetArrangeInfo({ arrangeId: params.rowData.arrangeId })
    if (acceptType === 'copy') {
      data.arrangeId = ''
    }
    data.limitClass = data.limitClass ? data.limitClass.split(',') : []
    data.limitGrade = data.limitGrade ? data.limitGrade.split(',') : []
    data.arrangeTimeList = data.arrangeTimeList === null ? [{ week: '', startTime: '', endTime: '' }] : data.arrangeTimeList
    Object.assign(form, data)
  }
};
/** 新增上课时间 */
function handleAddTime() {
  form.arrangeTimeList.push(_.cloneDeep(arrangeTime))
}
/** 删除上课时间 */
function handleDelTime(index: number) {
  if (form.arrangeTimeList.length > 1) {
    form.arrangeTimeList.splice(index, 1)
  }
}
const formRef = ref<FormInstance>()
function handleClose() {
  formRef.value!.resetFields()
  form.arrangeId = '';
  form.signupStartTime = '';
  form.signupEndTime = '';
  form.arrangeTimeList = [_.cloneDeep(arrangeTime)]
  visible.value = false
}
async function handleConfirm() {
  await formRef.value!.validate(async (valid) => {
    if (valid) {
      const { signupStartTime, signupEndTime } = form;
      if ((signupStartTime && !signupEndTime) || (!signupStartTime && signupEndTime)) {
        ElMessage.warning({ message: '开始时间和结束时间必须同时填写' });
        return
      }
      if (new Date(signupStartTime) > new Date(signupEndTime)) {
        ElMessage.warning({ message: '开始时间不能晚于结束时间' });
        return;
      }
      form.arrangeTimeList = form.arrangeTimeList.map((item: any) => {
        if (item.week !== undefined && item.startTime && item.endTime) {
          item.startTime = dayjs('1970-01-01 ' + item.startTime).format('HH:mm')
          item.endTime = dayjs('1970-01-01 ' + item.endTime).format('HH:mm')
          return item
        }
      })
      form.arrangeId ? await SaveArrange(form) : await AddArrange(form)
      ElMessage.success({ message: '操作成功' });
      props.value.getTableList!();
      handleClose()
    }
  })
}
defineExpose({
  acceptParams
});
</script>
<style lang='scss' scoped>
.flex-item {
  display: flex;
  justify-content: space-between;

  >div {
    flex: 1;

    &:first-of-type {
      margin-right: 20px;
    }

    &:last-of-type {
      margin-left: 20px;
    }
  }
}

.time-box,
.teacher-box {
  display: flex;
  align-items: center;

  &:not(:last-of-type) {
    margin-bottom: 14px;
  }

  .select-time-box {
    display: flex;
  }

  :deep(.select-item) {
    width: 160px !important;
    margin-right: 14px;
  }
}

.fix {
  margin-right: 14px;
  color: #666;
}

.setting-button {
  width: 100%;
  margin-bottom: 18px;
}

.content {
  margin-left: 22px;
  line-height: 30px;
  color: #777;
  font-size: 13px;
}

.flex-tag {
  display: flex;
  flex-wrap: wrap;

  :deep(.el-tag) {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  :deep(.el-input) {
    width: 130px;
  }
}
</style>